package com.example.test.httpclient;

import com.alibaba.fastjson.JSONObject;
import com.example.test.entity.User;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import java.util.LinkedList;
import java.util.List;

public class HttpClientPost {
    public static void main(String[] args) {
        doPost();
    }
    public static void doPost(){
        //1.获取连接客户端的工具
        CloseableHttpClient client= HttpClients.createDefault();
        try {
            //2.设置url地址
            //URIBuilder uriBuilder=new URIBuilder("http://127.0.0.1:8080/httpClientGet");
            //3.创建Post请求
            HttpPost httpPost=new HttpPost("http://127.0.0.1:8080/httpClientPost");
            //4.设置请求参数
            List<NameValuePair>list=new LinkedList<>();
            NameValuePair param1=new BasicNameValuePair("name","小黑");
            NameValuePair param2=new BasicNameValuePair("sex","男");
            NameValuePair param3=new BasicNameValuePair("age","22");
            list.add(param1);
            list.add(param2);
            list.add(param3);
            //5.URL 实体转化工具
            UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(list,"UTF-8");
            httpPost.setEntity(formEntity);
            /*
             * 添加请求头信息
             */
            // 浏览器表示
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            // 传输的类型
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.addHeader("header","post");
            //6.执行请求
            CloseableHttpResponse response=client.execute(httpPost);

            if(response.getStatusLine().getStatusCode()==200){
                // 7.获取响应体
                HttpEntity httpEntity=response.getEntity();
                //8.将响应体转为字符串格式
                String result= EntityUtils.toString(httpEntity,"UTF-8");
                //转化成Json格式
                JSONObject jsonObject=JSONObject.parseObject(result);
                System.out.println(result+","+jsonObject);
                System.out.println("Protocl:"+response.getStatusLine().getProtocolVersion());
                System.out.println("访问成功!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
